package com.lxf.net;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;

import org.jdom.DocType;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;


/**
 * 存放通用方法的类
 * Title: CommonFun.java
 * @author lixiaofeng
 * @date 2015年12月29日
 * @version 1.0
 */
public class UrlUtil {
	
	/**
	 * 根据链接获取内容并转为字符串
	 * @param dataUrl	url链接
	 * @return String
	 * @throws Exception
	 */
	public static String getString(String dataUrl) throws Exception{
		StringBuffer sb = new StringBuffer();
		String str = null;
		URL url = new URL(dataUrl);
		URLConnection uc =url.openConnection();
		//实践证明这样方法更好一点;对乱码处理比较好
		Reader reader = new BufferedReader(new InputStreamReader(uc.getInputStream()));
		//Reader reader = new InputStreamReader(new BufferedInputStream(uc.getInputStream())); 
	    int c; 
	    while ((c = reader.read()) != -1) { 
	  	  sb.append((char)c);
	    } 
	    reader.close();
	    str = sb.toString();
		return str;
	}
	
	/**
	 * 根据ua标识和链接获取内容并转为字符串
	 * @param dataUrl
	 * @param UA	是否设置UA标识
	 * @return	String
	 * @throws Exception
	 */
	public static String getString(String dataUrl, boolean UA) throws Exception{
		StringBuffer sb = new StringBuffer();
		String str = null;
		URL url = new URL(dataUrl);
		URLConnection uc =url.openConnection();
		
		/**
		 *  防止HTTP response code: 403;
		 *  需设置user-agent参数
		 */
		if(UA){
			uc.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
		}
		Reader reader = new BufferedReader(new InputStreamReader(uc.getInputStream()));
		//Reader reader = new InputStreamReader(new BufferedInputStream(uc.getInputStream())); 
	    int c; 
	    while ((c = reader.read()) != -1) { 
	  	  sb.append((char)c);
	    } 
	    reader.close();
	    str = sb.toString();
		return str;
	}
	
	/**
	 * 根据url链接和对应编码获取内容并转为字符串
	 * @param dataUrl	url链接
	 * @param encode	编码（GBK,UTF-8...）
	 * @return	String
	 * @throws Exception
	 */
	public static String getString(String dataUrl, String encode) throws Exception{
		StringBuffer sb = new StringBuffer();
		String str = null;
		URL url = new URL(dataUrl);
		URLConnection uc =url.openConnection();
		Reader reader;
		if(encode!=null && !encode.equals("")){
			reader = new BufferedReader(new InputStreamReader(uc.getInputStream(),encode));
			//reader = new InputStreamReader(new BufferedInputStream(uc.getInputStream()),encode);
		}else{
			reader = new BufferedReader(new InputStreamReader(uc.getInputStream()));
			//reader = new InputStreamReader(new BufferedInputStream(uc.getInputStream())); 
		}
	    int c; 
	    while ((c = reader.read()) != -1) { 
	  	  sb.append((char)c);
	    } 
	    reader.close();
	    str = sb.toString();
		return str;
	}
	
	/**
	 *  根据ua标识,对应编码和url链接获取内容并转为字符串
	 * @param dataUrl
	 * @param encode	编码类型（GBK，UTF-8...）
	 * @param UA	是否设置UA
	 * @return	String
	 * @throws Exception
	 */
	public static String getString(String dataUrl, String encode, boolean UA) throws Exception{
		StringBuffer sb = new StringBuffer();
		String str = null;
		URL url = new URL(dataUrl);
		URLConnection uc =url.openConnection();
		if(UA){
			uc.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
		}
		Reader reader;
		if(encode!=null && !encode.equals("")){
			reader = new BufferedReader(new InputStreamReader(uc.getInputStream(),encode));
			//reader = new InputStreamReader(new BufferedInputStream(uc.getInputStream()),encode);
		}else{
			reader = new BufferedReader(new InputStreamReader(uc.getInputStream()));
			//reader = new InputStreamReader(new BufferedInputStream(uc.getInputStream())); 
		}
	    int c; 
	    while ((c = reader.read()) != -1) { 
	  	  sb.append((char)c);
	    } 
	    reader.close();
	    str = sb.toString();
		return str;
	}
	
	/**
	 * 将数据写入文件
	 * @param path	文件路径
	 * @param root	Element根节点
	 * @throws Exception
	 */
	public static void saveFile(String path, Element root) throws Exception{
		//文件不存在就创建
		FileUtil.createFile(path);
		DocType dtype = new DocType("xml");//文档类型 
    	Document doc = new Document(root,dtype);//然后用root创建XML文档对象 
    	Format format = Format.getPrettyFormat();
    	XMLOutputter out = new XMLOutputter(format);
    	out.output(doc, new FileOutputStream(path));
	}

}
